/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.teacher.service.impl;

import com.fanrenqiji.entity.WeChatUserEntity;
import com.fanrenqiji.modules.business.wechatuser.dao.WeChatUserDao;
import com.fanrenqiji.modules.sys.dao.OfficeDao;
import com.fanrenqiji.modules.sys.dao.RoleDao;
import com.fanrenqiji.modules.sys.dao.UserDao;
import com.fanrenqiji.modules.sys.entity.Office;
import com.fanrenqiji.modules.sys.entity.Role;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.service.OfficeService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fanrenqiji.common.security.Digests;
import com.google.common.collect.Lists;

import com.fanrenqiji.entity.TeacherEntity;
import com.fanrenqiji.modules.business.teacher.vo.TeacherVO;
import com.fanrenqiji.modules.business.teacher.dao.TeacherDao;
import com.fanrenqiji.modules.business.teacher.service.TeacherService;

import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.fanrenqiji.common.persistence.Page;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 教师信息表业务逻辑实现
 *
 * @author wentao
 */
@Service(value = "teacher")
@Transactional(readOnly = true)
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private OfficeDao officeDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private RoleDao roleDao;

    @Autowired
    DozerBeanMapper beanMapper;

    /**
     * 插入
     *
     * @param teacher 插入的对象
     * @return 插入数据条数
     */
    @Transactional
    public TeacherVO insert(TeacherVO teacher) {
        TeacherEntity teacherEntity = new TeacherEntity();
        beanMapper.map(teacher, teacherEntity);
        teacherDao.save(teacherEntity);
        beanMapper.map(teacherEntity, teacher);
        return teacher;
    }


    /**
     * 批量插入
     *
     * @param list 数据列表
     * @return 插入数据条数
     */
    @Transactional
    public void insertList(List<TeacherVO> list) {
        for (TeacherVO teacher : list) {
            insert(teacher);
        }
    }


    /**
     * 修改
     *
     * @param teacher 修改的数据
     * @return 修改的数据
     */
    @Transactional
    public TeacherVO update(TeacherVO teacher) {
        TeacherEntity teacherEntity = null;
        if (StringUtils.isNotEmpty(teacher.getId())) {
            teacherEntity = teacherDao.findOne(Long.parseLong(teacher.getId()));
        }
        if (teacherEntity == null) {
            teacherEntity = new TeacherEntity();
        }
        if (StringUtils.isBlank(teacher.getPassword())) teacher.setPassword(teacherEntity.getPassword());
        beanMapper.map(teacher, teacherEntity);
        teacherEntity= teacherDao.save(teacherEntity);
        //判断是否需要穿件系统用户
        // 1.机构id=7（总公司） 2.状态 status=1（激活） 3.教师类别 type=1,3,4（教师类型 0:未分类 1:班主任 2:辅导老师 3:讲师  4:全部）
        if (teacherEntity.getCompanyId()==7L && teacherEntity.getStatus()==1 && (teacherEntity.getType()==1 ||
                teacherEntity.getType()==3 || teacherEntity.getType()==4)){
            if (teacherEntity.getPhone()!=null && StringUtils.isNotEmpty(teacherEntity.getPhone())){
                DetachedCriteria dc =userDao.createDetachedCriteria();
                dc.add(Restrictions.eq("mobile",teacherEntity.getPhone()));
                dc.add(Restrictions.eq(User.DEL_FLAG, User.DEL_FLAG_NORMAL));
                List<User> users = userDao.find(dc);
                //查到该状态
                if (users!=null && users.size()>0 ){
                    for (User user : users) {
                        user.setUserState("ACTIVE");
                        userDao.save(user);
                    }
                }else {
                    //查不到 创建
                    User user=new User();
                    user.setLoginName(teacherEntity.getPhone());//登录名
                    user.setMobile(teacherEntity.getPhone());//手机号码
                    user.setName(teacherEntity.getName());//姓名
                    user.setPassword(Digests.entryptPassword(teacherEntity.getPassword()));//设置密码
                    Office office = officeService.findById(teacherEntity.getCompanyId());
                    user.setCompany(office);//机构
                    user.setOffice(office);//机构
                    user.setUserState("ACTIVE");//状态
                    List<Role> roles=new ArrayList<Role>();
                    Role one = roleDao.findOne(19L);
                    if (one!=null)roles.add(one);
                    user.setRoleList(roles);
                    userDao.save(user);
                }
            }
        }
        //判断是否需要将系统用户禁用
        if (teacherEntity.getStatus()!=1 && teacherEntity.getPhone()!=null && StringUtils.isNotEmpty(teacherEntity.getPhone())){
            DetachedCriteria dc =userDao.createDetachedCriteria();
            dc.add(Restrictions.eq(User.DEL_FLAG, User.DEL_FLAG_NORMAL));
            dc.add(Restrictions.eq("mobile",teacherEntity.getPhone()));
            List<User> users = userDao.find(dc);
            if (users!=null && users.size()>0 ){
                for (User user : users) {
                    user.setUserState("INACTIVE");
                    userDao.save(user);
                }
            }
        }
        beanMapper.map(teacherEntity, teacher);
        return teacher;
    }


    /**
     * 删除
     *
     * @param id 数据标识
     * @return 删除的数据条数
     */
    @Transactional
    public void delete(String id) {
        teacherDao.deleteById(Long.parseLong(id));
    }


    /**
     * 查询所有数据
     *
     * @return 数据列表
     */
    public List<TeacherVO> getAll() {
        List<TeacherVO> list = Lists.newArrayList();
        List<TeacherEntity> entities = teacherDao.findAllList();
        for (TeacherEntity teacherEntity : entities) {
            TeacherVO teacherVO = new TeacherVO();
            beanMapper.map(teacherEntity, teacherVO);
            list.add(teacherVO);
        }
        return list;
    }


    /**
     * 通过条件查询数据列表
     *
     * @param teacher 查询条件
     * @return 数据列表
     */
    public List<TeacherVO> getList(TeacherVO teacher) {
        List<TeacherVO> list = Lists.newArrayList();
        DetachedCriteria dc = teacherDao.createDetachedCriteria();
        dc.add(Restrictions.eq(TeacherEntity.DEL_FLAG, TeacherEntity.DEL_FLAG_NORMAL));
       // 如果状态不为空 那么就按照这个来
        if(StringUtils.isNotBlank(teacher.getStatus())){
            String status = teacher.getStatus();
            dc.add(Restrictions.eq("status",Integer.parseInt(status)));

        }

    /*
     // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.like("name", "%" + teacher.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.eq("name", teacher.getName()));
    }

	dc.addOrder(Order.asc("office.id")).addOrder(Order.asc("name"));

    */
        List<TeacherEntity> entities = teacherDao.find(dc);
        for (TeacherEntity teacherEntity : entities) {
            TeacherVO teacherVO = new TeacherVO();
            beanMapper.map(teacherEntity, teacherVO);
            list.add(teacherVO);
        }
        return list;
    }


    /**
     * 通过id查询数据
     *
     * @param id 数据标识
     * @return 数据对象
     */
    public TeacherVO get(String id) {
        TeacherVO teacher = new TeacherVO();
        TeacherEntity teacherEntity = teacherDao.findOne(Long.parseLong(id));
        if (teacherEntity == null) {
            teacherEntity = new TeacherEntity();
        }
        beanMapper.map(teacherEntity, teacher);
        Office office = officeDao.findOne(teacherEntity.getCompanyId());
        teacher.setOffice(office);
        return teacher;
    }


    /**
     * 根据条件分页查询
     *
     * @param page
     * @param teacher
     * @return
     */
    public Page<TeacherVO> findTeacherByPage(Page<TeacherVO> page, TeacherVO teacher) {
        Page<TeacherEntity> pageEntity = new Page<TeacherEntity>(page.getPageNo(), page.getPageSize());
        DetachedCriteria dc = teacherDao.createDetachedCriteria();
        dc.add(Restrictions.eq(TeacherEntity.DEL_FLAG, TeacherEntity.DEL_FLAG_NORMAL));
        if (StringUtils.isNotEmpty(teacher.getName())) {
            dc.add(Restrictions.like("name", "%" + teacher.getName() + "%")); //like
        }
        if (StringUtils.isNotEmpty(teacher.getType())){
            dc.add(Restrictions.eq("type",Integer.parseInt(teacher.getType())));
        }
        if (StringUtils.isNotEmpty(teacher.getStatus())){
            dc.add(Restrictions.eq("status",Integer.parseInt(teacher.getStatus())));
        }
        if (StringUtils.isNotEmpty(teacher.getCompanyId())){
            dc.add(Restrictions.eq("companyId",Long.parseLong(teacher.getCompanyId())));
        }
        dc.createAlias("office", "office");
        User currentUser = UserUtils.getUser();
        if (currentUser.getOffice() != null && currentUser.getOffice().getId() != null){
            dc.add(Restrictions.or(
                    Restrictions.eq("office.id", currentUser.getOffice().getId()),
                    Restrictions.like("office.parentIds", "%,"
                            + currentUser.getOffice().getId() + ",%")));
        }

    /*
    dc.createAlias("teacher", "teacher"); // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.like("name", "%" + teacher.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.eq("name", teacher.getName()));
    }

    if (!StringUtils.isNotEmpty(page.getOrderBy())) {
	    dc.addOrder(Order.asc("name"))
		  .addOrder(Order.desc("id"));
	}
    */
        if(!StringUtils.isNotEmpty(page.getOrderBy())){
            dc.addOrder(Order.desc("id"));
        }
        pageEntity=teacherDao.find(pageEntity,dc);
       /* beanMapper.map(pageEntity,page);*/
        beanMapper.map(pageEntity,page);
        List<TeacherVO>list=Lists.newArrayList();
        for(TeacherEntity teacherEntity:pageEntity.getList()){
            TeacherVO teacherVO=new TeacherVO();
            beanMapper.map(teacherEntity,teacherVO);
            //添加office对象 手动维护
            Office office = new Office();

            if (StringUtils.isNotEmpty(teacherEntity.getCompanyId().toString())){
                office = officeDao.findOne( teacherEntity.getCompanyId());
            }
            teacherVO.setOffice(office);
            list.add(teacherVO);
        }
        page.setList(list);
        return page;
    }

    /**
     * 根据条件分页查询
     *
     * @param page
     * @param teacher
     * @return
     */
    public Page<TeacherVO> findTeacherByPage2(Page<TeacherVO> page, TeacherVO teacher) {
        Page<TeacherEntity> pageEntity = new Page<TeacherEntity>(page.getPageNo(), page.getPageSize());
        DetachedCriteria dc = teacherDao.createDetachedCriteria();
        dc.add(Restrictions.eq(TeacherEntity.DEL_FLAG, TeacherEntity.DEL_FLAG_NORMAL));
        if (StringUtils.isNotEmpty(teacher.getName())) {
            dc.add(Restrictions.like("name", "%" + teacher.getName() + "%")); //like
        }
        if (StringUtils.isNotEmpty(teacher.getType())){
            dc.add(Restrictions.eq("type",Integer.parseInt(teacher.getType())));
        }
        if (StringUtils.isNotEmpty(teacher.getStatus())){
            dc.add(Restrictions.eq("status",Integer.parseInt(teacher.getStatus())));
        }
        if (StringUtils.isNotEmpty(teacher.getCompanyId())){
            dc.add(Restrictions.eq("companyId",Long.parseLong(teacher.getCompanyId())));
        }
        dc.add(Restrictions.or(Restrictions.eq("type",3),Restrictions.eq("type",4)));
        dc.createAlias("office", "office");
        User currentUser = UserUtils.getUser();
        if (currentUser.getOffice() != null && currentUser.getOffice().getId() != null){
            dc.add(Restrictions.or(
                    Restrictions.eq("office.id", currentUser.getOffice().getId()),
                    Restrictions.like("office.parentIds", "%,"
                            + currentUser.getOffice().getId() + ",%")));
        }

    /*
    dc.createAlias("teacher", "teacher"); // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.like("name", "%" + teacher.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(teacher.getName())) {
        dc.add(Restrictions.eq("name", teacher.getName()));
    }

    if (!StringUtils.isNotEmpty(page.getOrderBy())) {
	    dc.addOrder(Order.asc("name"))
		  .addOrder(Order.desc("id"));
	}
    */
        if(!StringUtils.isNotEmpty(page.getOrderBy())){
            dc.addOrder(Order.desc("id"));
        }
        pageEntity=teacherDao.find(pageEntity,dc);
       /* beanMapper.map(pageEntity,page);*/
        beanMapper.map(pageEntity,page);
        List<TeacherVO>list=Lists.newArrayList();
        for(TeacherEntity teacherEntity:pageEntity.getList()){
            TeacherVO teacherVO=new TeacherVO();
            beanMapper.map(teacherEntity,teacherVO);
            //添加office对象 手动维护
            Office office = new Office();

            if (StringUtils.isNotEmpty(teacherEntity.getCompanyId().toString())){
                office = officeDao.findOne( teacherEntity.getCompanyId());
            }
            teacherVO.setOffice(office);
            list.add(teacherVO);
        }
        page.setList(list);
        return page;
    }

}
